package com.atguigu.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Properties;

/**
 *  消费者
 */
public class ConsumerDemo2 {
    public static void main(String[] args) {
        //1. 创建消费者对象
        Properties properties = new Properties();
        // 指定集群的位置
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092,hadoop103:9092,hadoop104:9092");
        // 消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "g3");
        // 自动提交offset
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        // 自动提交offset的间隔
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 1000);

        // K 和  V的反序列化器
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        //设置分区器
        //properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");
        properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.StickyAssignor");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //2. 调用方法消费数据
        //订阅主题
        ArrayList<String> topics = new ArrayList<>();
        topics.add("first");
        //topics.add("second");
        //topics.add("third");
        consumer.subscribe(topics);

        //持续消费
        while(true){
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(2));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println("消费到: " + record.topic() + " : "
                        + record.partition() + " : "
                        + record.offset() + " : "
                        + record.key() + " : "
                        + record.value());
            }

        }
        //3. 关闭消费者对象
        //consumer.close();
    }
}
